import { Response } from 'express'
interface IResponse<T> {
    code: number
    message: string
    data: T
}

export const ok = <T>(res: Response, data: T) => {
    const response: IResponse<T> = { code: 200, message: '成功', data }
    res.send(response)
}

export const fail = (res: Response, data: any) => {
    const response: IResponse<any> = { code: 500, message: '失败', data }
    res.send(response)
}

export const commonResponse = async <T, K>(res: Response, callback: () => Promise<T>) => {
    try {
        const response = await callback() as { code: number, data: K };
        (response.code as number) === 200 ? ok<K>(res, response.data) : fail(res, response.data)
    } catch (e: any) { fail(res, e) }
}